const express = require('express');
const { authenticateMiniappToken } = require('../middleware/auth');
const Order = require('../models/Order');
const Product = require('../models/Product');
const WechatPayService = require('../utils/WechatPayService');

const router = express.Router();

// 添加请求日志中间件
router.use((req, res, next) => {
  console.log(`小程序API请求: ${req.method} ${req.originalUrl}`);
  next();
});

// 所有小程序路由都需要认证
router.use(authenticateMiniappToken);

/**
 * 生成订单号
 */
function generateOrderNumber() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hour = String(now.getHours()).padStart(2, '0');
  const minute = String(now.getMinutes()).padStart(2, '0');
  const second = String(now.getSeconds()).padStart(2, '0');
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  
  return `PK${year}${month}${day}${hour}${minute}${second}${random}`;
}

/**
 * 创建订单
 * POST /api/miniapp/orders
 */
router.post('/orders', async (req, res) => {
  try {
    const userId = req.user.userId;
    const {
      items = [],
      contact_name,
      contact_phone,
      customer_notes = '',
      shipping_address
    } = req.body;

    console.log('接收到的订单数据:', {
      items: items.length,
      contact_name,
      contact_phone,
      customer_notes,
      shipping_address
    });

    // 验证必填字段
    if (!Array.isArray(items) || items.length === 0) {
      return res.error('订单商品不能为空', 400);
    }

    if (!contact_name || !contact_phone) {
      return res.error('请填写联系信息', 400);
    }

    // 验证收货地址
    if (!shipping_address || !shipping_address.recipient_name || !shipping_address.phone_number || 
        !shipping_address.province || !shipping_address.city || !shipping_address.district || 
        !shipping_address.detailed_address) {
      return res.error('请填写完整的收货地址', 400);
    }

    // 验证手机号格式
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(contact_phone)) {
      return res.error('请输入正确的手机号', 400);
    }

    // 验证商品信息并计算总金额
    let totalAmount = 0;
    const validatedItems = [];

    for (const item of items) {
      const { product_id, quantity } = item;
      
      if (!product_id || !quantity || quantity <= 0) {
        return res.error('商品信息不完整', 400);
      }

      // 获取商品信息
      let product;
      try {
        product = await Product.getById(product_id);
      } catch (error) {
        // 处理商品不存在等业务异常
        if (error.message === '商品不存在') {
          return res.error(`商品不存在: ${product_id}`, 400);
        }
        // 其他数据库或系统错误继续抛出
        throw error;
      }

      if (product.status !== 'active') {
        return res.error(`商品已下架: ${product.name}`, 400);
      }

      // 检查库存
      if (product.stock_quantity < quantity) {
        return res.error(`商品库存不足: ${product.name}，当前库存: ${product.stock_quantity}`, 400);
      }

      const itemTotal = product.price * quantity;
      totalAmount += itemTotal;

      validatedItems.push({
        product_id: product.id,
        quantity: quantity,
        price: product.price,
        product_name: product.name,
        product_image_url: product.main_image_url
      });
    }

    // 计算实际支付金额（不包含配送费）
    const paymentAmount = totalAmount;

    // 生成订单号
    const orderNumber = generateOrderNumber();

    // 创建订单数据
    const orderData = {
      order_number: orderNumber,
      user_id: userId,
      total_amount: totalAmount,
      shipping_fee: 0,
      payment_amount: paymentAmount,
      contact_info: {
        name: contact_name,
        phone: contact_phone
      },
      shipping_address: {
        recipient_name: shipping_address.recipient_name,
        phone_number: shipping_address.phone_number,
        province: shipping_address.province,
        city: shipping_address.city,
        district: shipping_address.district,
        detailed_address: shipping_address.detailed_address
      },
      customer_notes: customer_notes,
      items: validatedItems
    };

    // 创建订单
    const order = await Order.create(orderData);

    res.success({
      order_id: order.id,
      order_number: orderNumber,
      payment_amount: paymentAmount,
      total_amount: totalAmount,
      shipping_fee: 0
    }, '订单创建成功');

  } catch (error) {
    console.error('创建订单失败:', error);
    res.error(error.message || '创建订单失败', 500);
  }
});

/**
 * 获取用户订单列表
 * GET /api/miniapp/orders
 */
router.get('/orders', async (req, res) => {
  try {
    const userId = req.user.userId;
    const {
      page = 1,
      pageSize = 10,
      status = null
    } = req.query;

    const result = await Order.getList({
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      user_id: userId,
      status,
      sort: 'created_at',
      order: 'DESC'
    });

    res.success({
      orders: result.orders,
      total: result.total,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    }, '获取订单列表成功');

  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.error('获取订单列表失败', 500, error.message);
  }
});

/**
 * 获取订单详情
 * GET /api/miniapp/orders/:id
 */
router.get('/orders/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    
    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    // 验证订单是否属于当前用户
    if (order.user_id !== userId) {
      return res.error('无权限访问此订单', 403);
    }

    res.success(order, '获取订单详情成功');

  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.error('获取订单详情失败', 500, error.message);
  }
});

/**
 * 取消订单
 * PUT /api/miniapp/orders/:id/cancel
 */
router.put('/orders/:id/cancel', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    
    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    // 验证订单是否属于当前用户
    if (order.user_id !== userId) {
      return res.error('无权限操作此订单', 403);
    }

    // 只有待支付的订单可以取消
    if (order.status !== 'pending_payment') {
      return res.error('当前订单状态不允许取消', 400);
    }

    // 更新订单状态为已取消
    const updatedOrder = await Order.updateStatus(id, 'cancelled');

    res.success(updatedOrder, '订单取消成功');

  } catch (error) {
    console.error('取消订单失败:', error);
    res.error('取消订单失败', 500, error.message);
  }
});

/**
 * 申请退款 (待发货订单)
 * POST /api/miniapp/orders/:id/refund
 */
router.post('/orders/:id/refund', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    const { reason = '用户主动申请退款' } = req.body;
    
    // 获取订单信息
    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    // 验证订单是否属于当前用户
    if (order.user_id !== userId) {
      return res.error('无权限操作此订单', 403);
    }

    // 只有待发货(processing)状态的订单可以申请退款
    if (order.status !== 'processing') {
      return res.error('只有待发货订单才能申请退款', 400);
    }

    // 检查订单是否已支付
    if (!order.transaction_id) {
      return res.error('订单尚未支付，无需退款', 400);
    }

    // 生成退款单号
    const refundNo = WechatPayService.generateRefundNumber(order.order_number);
    
    // 检查transaction_id是否为有效的微信支付订单号（1-32位纯数字）
    const isValidWechatTransactionId = /^\d{1,32}$/.test(order.transaction_id);
    let realTransactionId = order.transaction_id;
    
    // 如果transaction_id不是有效格式（如manual_或mock_开头），尝试查询微信获取真实订单号
    if (!isValidWechatTransactionId) {
      console.log(`检测到非标准transaction_id: ${order.transaction_id}，尝试查询微信支付状态`);
      
      try {
        const queryResult = await WechatPayService.queryOrder(order.order_number);
        if (queryResult.success && queryResult.data && queryResult.data.transaction_id) {
          realTransactionId = queryResult.data.transaction_id;
          console.log(`从微信查询到真实transaction_id: ${realTransactionId}`);
          
          // 更新订单的transaction_id为真实的微信订单号
          await Order.updateStatus(order.id, order.status, {
            transaction_id: realTransactionId
          });
        } else {
          console.log('未能从微信查询到真实transaction_id，将使用商户订单号进行退款');
          realTransactionId = null; // 使用商户订单号退款
        }
      } catch (queryError) {
        console.error('查询微信支付状态失败:', queryError);
        realTransactionId = null; // 使用商户订单号退款
      }
    }
    
    const refundResult = await WechatPayService.refund({
      transactionId: realTransactionId,    // 使用真实的微信支付订单号（如果有的话）
      outTradeNo: order.order_number,      // 商户订单号
      outRefundNo: refundNo,               // 退款单号
      reason: reason,                      // 退款原因
      refundAmount: order.payment_amount,  // 退款金额
      totalAmount: order.payment_amount    // 原订单金额
    });

    if (!refundResult.success) {
      return res.error('退款申请失败: ' + refundResult.error, 500);
    }

    // 更新订单状态为已退款
    await Order.updateStatus(id, 'refunded');
    
    // 记录退款信息（可以考虑在订单表中增加退款相关字段）
    console.log('退款申请成功:', {
      orderId: id,
      orderNumber: order.order_number,
      refundNo: refundNo,
      refundId: refundResult.refundId,
      amount: order.payment_amount,
      reason: reason
    });

    res.success({
      refundNo: refundNo,
      refundId: refundResult.refundId,
      status: refundResult.status,
      mockMode: refundResult.mockMode
    }, '退款申请成功，将在1-3个工作日内处理完成');

  } catch (error) {
    console.error('申请退款失败:', error);
    res.error('申请退款失败', 500, error.message);
  }
});

/**
 * 创建微信支付订单
 * POST /api/miniapp/orders/:id/pay
 */
router.post('/orders/:id/pay', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;

    // 获取订单信息
    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    // 验证订单是否属于当前用户
    if (order.user_id !== userId) {
      return res.error('无权限操作此订单', 403);
    }

    // 如果订单已经支付，直接返回支付成功状态
    if (order.status === 'processing' || order.status === 'paid' || order.status === 'shipped' || order.status === 'completed') {
      return res.success({
        payment_status: 'paid',
        order_number: order.order_number,
        payment_amount: order.payment_amount,
        message: '订单已支付成功'
      }, '订单已支付成功');
    }

    // 只有待支付的订单可以支付
    if (order.status !== 'pending_payment') {
      return res.error('订单状态不允许支付', 400);
    }

    // 调用微信支付服务创建支付订单
    const paymentOrderData = {
      description: `珠宝订单-${order.order_number}`,
      outTradeNo: order.order_number,
      amount: order.payment_amount,
      openid: req.user.openid || 'mock_openid', // 从用户信息中获取openid
      timeExpire: new Date(Date.now() + 15 * 60 * 1000).toISOString() // 15分钟后过期
    };

    console.log('支付订单数据:', paymentOrderData);

    // 创建微信支付订单
    const payResult = await WechatPayService.createOrder(paymentOrderData);

    if (!payResult.success) {
      return res.error(payResult.error || '创建支付订单失败', 500);
    }

    // 如果订单已经支付，直接更新订单状态并返回成功
    if (payResult.alreadyPaid) {
      await Order.updateStatus(order.id, 'processing', {
        payment_time: new Date(),
        transaction_id: `wechat_${Date.now()}`,
        payment_method: 'wechat_pay'
      });

      return res.success({
        payment_status: 'paid',
        order_number: order.order_number,
        payment_amount: order.payment_amount,
        message: '订单已支付成功'
      }, '订单已支付成功');
    }

    // 生成小程序支付参数
    const paymentParams = WechatPayService.generatePaymentParams(payResult.prepayId);

    res.success({
      payment_data: paymentParams,
      order_number: order.order_number,
      payment_amount: order.payment_amount
    }, '支付订单创建成功');

  } catch (error) {
    console.error('创建支付订单失败:', error);
    res.error(error.message || '创建支付订单失败', 500);
  }
});

/**
 * 模拟支付成功（仅用于开发测试）
 * POST /api/miniapp/orders/:id/mock-pay-success
 */
router.post('/orders/:id/mock-pay-success', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;

    // 获取订单信息
    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    // 验证订单是否属于当前用户
    if (order.user_id !== userId) {
      return res.error('无权限操作此订单', 403);
    }

    // 只有待支付的订单可以模拟支付成功
    if (order.status !== 'pending_payment') {
      return res.error('订单状态不允许支付', 400);
    }

    // 更新订单状态为已支付
    await Order.updateStatus(order.id, 'processing', {
      payment_time: new Date(),
      transaction_id: `mock_${Date.now()}`,
      payment_method: 'wechat_pay'
    });

    console.log('模拟支付成功，订单状态已更新:', order.order_number);
    res.success({ status: 'processing' }, '模拟支付成功');

  } catch (error) {
    console.error('模拟支付失败:', error);
    res.error('模拟支付失败', 500, error.message);
  }
});

/**
 * 手动确认支付成功（用于真实支付后手动更新状态）
 * POST /api/miniapp/orders/:id/confirm-payment
 */
router.post('/orders/:id/confirm-payment', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;
    const { transaction_id } = req.body;

    // 获取订单信息
    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    // 验证订单是否属于当前用户
    if (order.user_id !== userId) {
      return res.error('无权限操作此订单', 403);
    }

    // 只有待支付的订单可以确认支付
    if (order.status !== 'pending_payment') {
      return res.error('订单状态不允许确认支付', 400);
    }

    // 更新订单状态为已支付
    await Order.updateStatus(order.id, 'processing', {
      payment_time: new Date(),
      transaction_id: transaction_id || `manual_${Date.now()}`,
      payment_method: 'wechat_pay'
    });

    console.log('手动确认支付成功，订单状态已更新:', order.order_number);
    res.success({ status: 'processing' }, '支付确认成功');

  } catch (error) {
    console.error('确认支付失败:', error);
    res.error('确认支付失败', 500, error.message);
  }
});

/**
 * 微信支付回调处理
 * POST /api/miniapp/payment/callback
 */
router.post('/payment/callback', async (req, res) => {
  try {
    console.log('收到微信支付回调:', JSON.stringify(req.body, null, 2));
    console.log('回调头部:', JSON.stringify(req.headers, null, 2));

    // TODO: 验证微信支付回调签名
    // 暂时跳过签名验证，实际项目中需要验证
    // const isValid = await WechatPayService.verifyCallback(req.headers, req.body);
    // if (!isValid) {
    //   return res.status(400).json({ code: 'FAIL', message: '签名验证失败' });
    // }

    const callbackData = req.body;

    // 微信支付V3回调数据结构可能不同，先尝试不同的解析方式
    let out_trade_no, transaction_id, trade_state;

    if (callbackData.resource && callbackData.resource.ciphertext) {
      // 加密数据需要解密，这里暂时跳过
      console.log('收到加密的回调数据，需要解密处理');
      return res.status(200).json({ code: 'SUCCESS', message: '收到加密数据' });
    } else if (callbackData.out_trade_no) {
      // 直接的数据结构
      out_trade_no = callbackData.out_trade_no;
      transaction_id = callbackData.transaction_id;
      trade_state = callbackData.trade_state;
    } else {
      console.log('未知的回调数据结构');
      return res.status(200).json({ code: 'SUCCESS', message: '未知数据结构' });
    }

    if (trade_state === 'SUCCESS') {
      // 查找订单
      const order = await Order.findByOrderNumber(out_trade_no);
      if (!order) {
        console.error('支付回调：订单不存在', out_trade_no);
        return res.status(400).json({ code: 'FAIL', message: '订单不存在' });
      }

      // 更新订单状态为已支付
      await Order.updateStatus(order.id, 'processing', {
        payment_time: new Date(),
        transaction_id: transaction_id,
        payment_method: 'wechat_pay'
      });

      console.log('支付成功，订单状态已更新:', out_trade_no);
    }

    // 返回成功响应给微信
    res.status(200).json({ code: 'SUCCESS', message: '成功' });

  } catch (error) {
    console.error('处理支付回调失败:', error);
    res.status(500).json({ code: 'FAIL', message: '处理失败' });
  }
});

/**
 * 查询支付状态
 * GET /api/miniapp/orders/:id/payment-status
 */
router.get('/orders/:id/payment-status', async (req, res) => {
  try {
    const { id } = req.params;
    const userId = req.user.userId;

    const order = await Order.findById(id);
    if (!order) {
      return res.error('订单不存在', 404);
    }

    // 验证订单是否属于当前用户
    if (order.user_id !== userId) {
      return res.error('无权限访问此订单', 403);
    }

    // TODO: 如果订单还是待支付状态，查询微信支付状态
    // 暂时直接返回当前订单状态，实际项目中需要查询微信支付状态
    // if (order.status === 'pending_payment') {
    //   try {
    //     const paymentStatus = await WechatPayService.queryOrder(order.order_number);
    //     // 处理支付状态...
    //   } catch (queryError) {
    //     console.error('查询微信支付状态失败:', queryError);
    //   }
    // }

    res.success({
      status: order.status,
      payment_time: order.payment_time,
      transaction_id: order.transaction_id
    }, '支付状态查询成功');

  } catch (error) {
    console.error('查询支付状态失败:', error);
    res.error('查询支付状态失败', 500, error.message);
  }
});

module.exports = router;
